﻿using B.S.BasicData.Api.Read.Application.Command.Menu;
using B.S.BasicData.Api.Read.DTO;
using B.S.BasicData.Domian.Entities.Menu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using System.Security.Cryptography;
using System;

namespace B.S.BasicData.Api.Read.Application.Handler.Menu
{
    public class GetMenuHandler : IRequestHandler<GetMenuCommand, ApiPaging<GetMenuDTO>>
    {
        private readonly IBaseRepository<MenuModel> meunRepo;

        public GetMenuHandler(IBaseRepository<MenuModel>meunRepo)
        {
            this.meunRepo = meunRepo;
        }
        public Task<ApiPaging<GetMenuDTO>> Handle(GetMenuCommand request, CancellationToken cancellationToken)
        {
            var res=new ApiPaging<GetMenuDTO>();
            var menu=meunRepo.GetAll().Where(x=>x.IsDel==false);
            var model =meunRepo.GetAll().Where(x=> x.IsDel==false);
            var linq = from a in menu
                       join b in model.DefaultIfEmpty() on a.Pid equals b.Id into abGroup
                       from b in abGroup.DefaultIfEmpty()
                       select new GetMenuDTO
                       {
                           Id = a.Id,
                           MenuName = a.MenuName,
                           Url = a.Url,
                           Pid = a.Pid,
                           ParentName = b.MenuName,
                           CreateBy = a.CreateBy,
                           CreateData = a.CreateData,
                           UpdateBy = a.UpdateBy,
                           UpdateData = a.UpdateData,
                       };
            var totalcount = linq.Count();
            var totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.PageSize);
            linq = linq.OrderByDescending(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            res.totalcount = totalcount;
            res.totalpage = totalpage;
            res.Message = "显示成功";
            res.Data = linq.ToList();
            res.Code = ApiEnum.Ok;
            return Task.FromResult(res);
        }
    }
}
